/**
 * Created by sunkejun on 2015/10/15.
 */

$(document).ready(function(){

    // activate Nestable for list 1

    //$('.dd').nestable('expandAll');




    admin_filecontents_list.init();
    admin_filecontents_list.getCategoryTree();


})
var admin_filecontents_list  = (function ($) {

    this.init = function() {

        //排序初始化
        $('#nestable').nestable({
            group: 1
        }).on('change',function(e){
            admin_filecontents_list.saveSortedCategory();
        })

        //checkbox 初始化
        $('.i-checks').iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green',
        });
        //富文本编辑器初始化
        $('#file_content').summernote({
            focus: true
        });

        this.addState();

    }

    this.getCategoryTree = function() {
        $.ajax({
            url:  '/admin/filecontents/getTreeData',
            type:"POST",
            dataType:'JSON',
            data: {},
            success:function(response){
                $('#nestable').html(initSortList(response) );

            }
        });
    }
    this.saveSortedCategory = function(){
        ComdataUtil.ajaxpost('/admin/filecontents/updateCtrees',{data:JSON.stringify($('#nestable').nestable('serialize'))},this.finishAjaxLoadBack);
    }


    this.initSortList = function(data){
        var str = '<ol class="dd-list">';
        for(var i=0;i<data.length;i++){
            str+=' <li class="dd-item dd-collapsed"  data-id="'+data[i].id+'">';
            if(data[i].children &&  data[i].children.length >0){
                str+= '<button   data-action="collapse" type="button" style="display: none;">Collapse</button><button data-action="expand" type="button" style="display: block;">Expand</button>';
            }
            str+='<div style="" class="dd-handle" > '+data[i].title+'</div>';

            if(data[i].children &&  data[i].children.length >0){
                str+= initSortList(data[i].children);
            }

            str+=' <a  class="btn btn-warning btn-xs"   style="position: absolute;right: 0;top: 5px; color" onclick="admin_filecontents_list.editClick('+data[i].id+')"><i class="fa fa-edit"></i></a>';
            //str+='<a style="position: absolute;right: 0;top: 5px;">xiug </a>';
             str+=' </li>';
        }
        str+=" </ol>";
        return str;
    }

    //点击添加新的页面
    this.addClick = function() {

        this.addState();
    }
    //修改点击
    this.editClick = function(id) {
         //alert(id);
        $('#p_delete').attr('editeid',id);
        $('#p_showhistory').attr('fileid',id);

        ComdataUtil.ajaxpostnormal('/admin/filecontents/'+id,{},function(data){
            //console.log(data);

            var target = $("div.note-editor button[data-event='codeview']");
            if($(target).hasClass('active')){
                $("div.note-editor button[data-event='codeview']").click();

            }


            ComdataUtil.clear("fileeditcontent");
            ComdataUtil.loadContainer("fileeditcontent",data);
            if(data){
                $('#file_content').code(data.page_content);
                $('#is_show').iCheck(data.is_show==0? 'uncheck':'check');
                $('#use_seo').iCheck(data.use_seo==1? 'check':'uncheck');

                $('#p_view').attr('href',admin_filecontents_list.getPUrl(data));
            }
            this.editState();
        },"GET")
    }

    this.getPUrl = function(data){
        var url = "/";
        if(data.parent_name){
            url+=data.parent_name+"/";
        }
        url+=data.name;
        return url;
    }

    this.delete = function(){
        var id = $('#p_delete').attr('editeid');
        swal({
            title: language.getNorlanguage().delete_title,
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: language.getNorlanguage().delete_sub,
            cancelButtonText: language.getNorlanguage().delete_cancle,
            closeOnConfirm: true,
            html: false
        }, function(){
            ComdataUtil.ajaxpostnormal('/admin/filecontents/'+id,{},function(data){
                //window.location = "/admin/filecontents";
                if(data.code == 200){
                    admin_filecontents_list.getCategoryTree();
                    this.addState();
                }else{
                    openToastr.open(3,data.res_data)
                }

            },"DELETE");
        });

    }


    this.saveSubmit = function() {
      //提交内容
        var target = $("div.note-editor button[data-event='codeview']");
        if($(target).hasClass('active')){
            $("div.note-editor button[data-event='codeview']").click();

        }

        $data = ComdataUtil.collectData("fileeditcontent");
        $data.page_content = $('#file_content').code();
        ComdataUtil.ajaxpost('/admin/filecontents',$data,function(data){
            if(data.code == 200){
                admin_filecontents_list.getCategoryTree();

                $('#p_view').attr('href',admin_filecontents_list.getPUrl($data));
            }else{
                openToastr.open(3,data.res_data)
            }
            //window.location = "/admin/filecontents";
        });
    }

    //添加模式
    this.addState = function() {
        ComdataUtil.clear("fileeditcontent");
        //$('#file_content').summernote('destroy');
        $('#file_content').code('');
        $('#p_view').hide();
        $('#p_showhistory').hide();
        $('#p_delete').hide();
    }
    //修改模式
    this.editState = function() {
        $('#p_view').show();
        $('#p_delete').show();
        $('#p_showhistory').show();
    }




    //选择父类
    this.selectNode = function(){
        var nodes = this.$tree.getSelectedNodes();
        if(nodes.length >0){
            $("#parent_name").val(nodes[0].name);
            $("#parent_id").val(nodes[0].id);
        }
        $("#category_modal").modal('hide');
    }
    this.openModel = function() {
        this.getCategorySelectTree();
        $("#category_modal").modal('show');
        //console.log($("#parent_id").val());
        if(this.$tree){
            var nodes = this.$tree.getNodesByParam("id", $("#parent_id").val(), null);
            if(nodes.length >0){
                this.$tree.selectNode(nodes[0]);
                $("#category_modal_current").html(nodes[0].name);
            }
        }

    }

    this.getCategorySelectTree = function() {
        $.ajax({
            url:  '/admin/filecontents/getTreeData',
            type:"POST",
            dataType:'JSON',
            data: {},
            success:function(response){
                initTree(response);
                //$('#nestable').html(initSortList(response) );

            }
        });
    }

    this.initTree = function(data){
        var setting = {
            callback: {
                onClick: this.treeCategorySelect
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parent_id"
                },
                key: {
                    name: "title",
                    //title: "title",
                }
            }
        };

        var zNodes =data;
        this.$tree = $.fn.zTree.init($("#category_tree"), setting, zNodes);
        var nodes = this.$tree.getNodesByParam("id", $("#parent_id").val(), null);

        if(nodes.length >0){
            this.$tree.selectNode(nodes[0], true, true);
        }
    }
    this.treeCategorySelect = function(event, treeId, treeNode){
        //alert(treeNode.tId + ", " + treeNode.name + "," + treeNode.checked);

        $("#category_modal_current").html(treeNode.name);

    }


    this.showHistorylist = function(){
        var id = $('#p_showhistory').attr('fileid');
        $("#content_history").modal('show');
        ComdataUtil.ajaxpostnormal('/admin/filecontents/getContentHistory',{id:id},function(data){
            if(data){

                for(var i=0;i<data.length;i++){
                    data[i].name = data[i].created_at+"/"+data[i].title;
                }
                var setting = {
                    callback: {
                        onClick: this.historySelect
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "id",
                            pIdKey: "parent_id"
                        },
                        key: {
                            name: "name",
                            //title: "title",
                        }
                    }
                };

                var zNodes =data;
                this.$historytree = $.fn.zTree.init($("#content_history_tree"), setting, zNodes);
            }
            //window.location = "/admin/filecontents";
        },"POST");

    }
    this.historySelect = function(event, treeId, treeNode){
        //alert(treeNode.tId + ", " + treeNode.name + "," + treeNode.checked);

        $("#history_modal_current").html(treeNode.name);

    }

    //选中历史版本号以后, 加载对应的历史版本数据, 载入当前页面
    this.choseHistoryItem = function(){
        $("#content_history").modal('hide');
        var nodes = this.$historytree.getSelectedNodes();
        if(nodes.length >0){
            $id = nodes[0].id;
            ComdataUtil.ajaxpostnormal('/admin/filecontents/getContentHistoryById',{id:$id},function(data){
                data.id = data.file_id;
                ComdataUtil.clear("fileeditcontent");
                ComdataUtil.loadContainer("fileeditcontent",data);
                if(data){
                    $('#file_content').code(data.page_content);
                    $('#is_show').iCheck(data.is_show==0? 'uncheck':'check');
                    $('#use_seo').iCheck(data.use_seo==0? 'uncheck':'check');

                    $('#p_view').attr('href',admin_filecontents_list.getPUrl(data));
                }
            },"POST");
        }
    }

    return this;
})(jQuery);

